package site.qjdb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import site.qjdb.constant.Info;
import site.qjdb.pojo.Comment;
import site.qjdb.pojo.Goods;
import site.qjdb.pojo.Notice;
import site.qjdb.pojo.User;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.pojo.response.ResponseCode;
import site.qjdb.service.CommentService;
import site.qjdb.service.GoodsService;
import site.qjdb.service.NoticeService;
import site.qjdb.service.UserService;
import site.qjdb.util.CommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

@Controller
@RequestMapping("/comment")
public class CommentController {
	@Resource
	private GoodsService goodsService;
	@Resource
	private UserService userService;
	@Resource
	private CommentService commentService;
	@Resource NoticeService noticeService;

	/**
	 *	添加留言 
	 * 	gid：对应的商品id，必传 
	 * 	content：留言内容，必传
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Object add(@RequestParam("id") String gid, 
			@RequestParam String content, 
			HttpServletRequest request,
			HttpServletResponse response, 
			HttpSession session) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if (i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		if ("".equals(content.trim())) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
		Integer gidInteger = null;
		try {
			gidInteger = Integer.parseInt(gid);
			// 根据gid查找Goods，查看状态是否为1（通过）
			Goods _goods = new Goods();
			_goods.setGid(gidInteger);
			_goods.setState(1);
			Goods newGoods = goodsService.findGoods(_goods);
			if (newGoods == null) {
				throw new Exception();
			}
			// 解决特殊字符是空白的问题
			content = URLDecoder.decode(URLEncoder.encode(content, "UTF-8"),"UTF-8");
			// 设置留言
			Comment comment = new Comment();
			// 留言内容
			comment.setContent(content);
			// 留言对应的商品
			comment.setGoods(_goods);
			// 发布留言的用户
			User _user = new User();
			_user.setUid((((User) session.getAttribute(Info.USER_SESSION)).getUid()));
			comment.setUser(_user);
			// 未删除
			comment.setIsDel(0);
			// 点赞数为0
			comment.setLikeCount(0);
			// 发布时间
			comment.setTime(new Date());
			// 添加留言
			commentService.addComment(comment);
			// 设置通知
			Notice notice = new Notice();
			// 对应留言id
			notice.setCommentId(comment.getCommentId());
			// 未删除
			notice.setIsDel(0);
			// 新通知
			notice.setIsNew(1);
			// 类型：回复我的商品（10）
			notice.setType(10);
			// 时间
			notice.setTime(new Date());
			// 接收用户
			notice.setUid(newGoods.getUser().getUid());
			// 添加通知
			noticeService.addNotice(notice);
			return new CommonResult<>(ResponseCode.SUCCESS, comment);
		} catch (Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
	}

	/**
	 * 	增加点赞数
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/like", method = RequestMethod.POST)
	public Object like(@RequestParam("id1") String commentId, 
			@RequestParam("id2") String gid,
			HttpServletRequest request, 
			HttpServletResponse response, 
			HttpSession session) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if (i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		Integer commentIdInteger = null;
		Integer gidInteger = null;
		try {
			gidInteger = Integer.parseInt(gid);
			// 根据gid查找Goods，查看状态是否为1（通过）
			Goods _goods = new Goods();
			_goods.setGid(gidInteger);
			_goods.setState(1);
			Goods newGoods = goodsService.findGoods(_goods);
			if (newGoods == null) {
				throw new Exception();
			}
			commentIdInteger = Integer.parseInt(commentId);
			// 根据commentId，gid查找Comment，查看是否存在
			Comment _comment = new Comment();
			_comment.setCommentId(commentIdInteger);
			_comment.setGoods(_goods);
			_comment.setIsDel(0);
			Comment newComment = commentService.findComment(_comment);
			if (newComment == null) {
				throw new Exception();
			}
			// 增加点赞数
			commentService.addLikeCount(newComment);
			// 设置通知
			Notice notice = new Notice();
			// 对应留言id
			notice.setCommentId(commentIdInteger);
			// 未删除
			notice.setIsDel(0);
			// 新通知
			notice.setIsNew(1);
			// 类型：点赞我的留言（20）
			notice.setType(20);
			// 时间
			notice.setTime(new Date());
			// 接收用户
			notice.setUid(newComment.getUser().getUid());
			// 设置点赞用户
			notice.setOtherUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
			// 添加通知
			noticeService.addNotice(notice);
			return new CommonResult<>(ResponseCode.SUCCESS);
		} catch (Exception e) {
			return new CommonResult<>(ResponseCode.COMMENT_NOT_FOUND);
		}
	}

	/**
	 * 	得到对应商品的留言
	 * 	gid：对应商品的id
	 * 
	 */
	@ResponseBody
	@RequestMapping("/getComments")
	public Object getComments(@RequestParam("id") String gid) {
		Integer gidInteger = null;
		try {
			gidInteger = Integer.parseInt(gid);
			// 根据gid查找Goods，查看状态是否为1（通过）
			Goods _goods = new Goods();
			_goods.setGid(gidInteger);
			_goods.setState(1);
			Goods newGoods = goodsService.findGoods(_goods);
			if (newGoods == null) {
				throw new Exception();
			}
			return new CommonResult<>(ResponseCode.SUCCESS, commentService.findCommentAll(gidInteger));
		} catch (Exception e) {
			return new CommonResult<>(ResponseCode.COMMENT_NOT_FOUND);
		}
	}
}
